<template>
  <NDrawer v-model:show="visible" :width="1000" title="质量报告详情">
    <NDrawerContent closable>
      <NSpin :show="loading">
        <NSpace vertical :size="16">
          <!-- 基本信息 -->
          <NCard title="基本信息" size="small">
            <NDescriptions :column="3" label-placement="left">
              <NDescriptionsItem label="表名">{{ report?.tableName }}</NDescriptionsItem>
              <NDescriptionsItem label="检查时间">{{ report?.checkTime }}</NDescriptionsItem>
              <NDescriptionsItem label="质量评分">
                <NTag :type="getScoreType(report?.qualityScore)">{{ report?.qualityScore?.toFixed(2) }}</NTag>
              </NDescriptionsItem>
              <NDescriptionsItem label="总记录数">{{ report?.totalCount }}</NDescriptionsItem>
              <NDescriptionsItem label="问题记录数">{{ report?.problemCount }}</NDescriptionsItem>
              <NDescriptionsItem label="问题率">{{ problemRate }}%</NDescriptionsItem>
            </NDescriptions>
          </NCard>

          <!-- 质量趋势图 -->
          <NCard title="质量趋势" size="small">
            <div ref="trendChartRef" style="width: 100%; height: 300px"></div>
          </NCard>

          <!-- 维度统计 -->
          <NCard title="维度统计" size="small">
            <NGrid :cols="2" :x-gap="16">
              <NGridItem>
                <div ref="dimensionChartRef" style="width: 100%; height: 300px"></div>
              </NGridItem>
              <NGridItem>
                <div ref="dimensionBarChartRef" style="width: 100%; height: 300px"></div>
              </NGridItem>
            </NGrid>
          </NCard>

          <!-- 问题分布 -->
          <NCard title="问题详情" size="small">
            <NDataTable
              :columns="problemColumns"
              :data="report?.problemDetails || []"
              size="small"
              :max-height="400"
              :pagination="{ pageSize: 10 }"
            />
          </NCard>
        </NSpace>
      </NSpin>
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { fetchQualityReportDetail, fetchQualityTrend, fetchDimensionStats } from '@/service/api';

interface Props {
  visible: boolean;
  reportId: number;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  reportId: 0
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}

const emit = defineEmits<Emits>();

const visible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
});

const loading = ref(false);
const report = ref<any>(null);
const trendData = ref<any>(null);
const dimensionStats = ref<any>(null);

const trendChartRef = ref<HTMLElement>();
const dimensionChartRef = ref<HTMLElement>();
const dimensionBarChartRef = ref<HTMLElement>();

let trendChart: ECharts | null = null;
let dimensionChart: ECharts | null = null;
let dimensionBarChart: ECharts | null = null;

const problemRate = computed(() => {
  if (!report.value || !report.value.totalCount) return 0;
  return ((report.value.problemCount / report.value.totalCount) * 100).toFixed(2);
});

const problemColumns = [
  { key: 'dimension', title: '质量维度', width: 120 },
  { key: 'ruleName', title: '违反规则', width: 150 },
  { key: 'problemCount', title: '问题数量', width: 100 },
  { key: 'problemDesc', title: '问题描述', minWidth: 200 }
];

function getScoreType(score?: number) {
  if (!score) return 'default';
  if (score >= 80) return 'success';
  if (score >= 60) return 'warning';
  return 'error';
}

async function loadReport() {
  if (!props.reportId) return;
  loading.value = true;
  try {
    const [reportRes, trendRes, statsRes] = await Promise.all([
      fetchQualityReportDetail(props.reportId),
      fetchQualityTrend(props.reportId),
      fetchDimensionStats(props.reportId)
    ]);
    report.value = reportRes.data;
    trendData.value = trendRes.data;
    dimensionStats.value = statsRes.data;
    await nextTick();
    renderCharts();
  } finally {
    loading.value = false;
  }
}

function renderCharts() {
  renderTrendChart();
  renderDimensionChart();
  renderDimensionBarChart();
}

function renderTrendChart() {
  if (!trendChartRef.value || !trendData.value) return;

  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value);
  }

  const dates = trendData.value.map((item: any) => item.date);
  const scores = trendData.value.map((item: any) => item.qualityScore);
  const problemRates = trendData.value.map((item: any) => item.problemRate);

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['质量评分', '问题率']
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: [
      {
        type: 'value',
        name: '质量评分',
        min: 0,
        max: 100
      },
      {
        type: 'value',
        name: '问题率(%)',
        min: 0,
        max: 100
      }
    ],
    series: [
      {
        name: '质量评分',
        type: 'line',
        data: scores,
        smooth: true,
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: '问题率',
        type: 'line',
        yAxisIndex: 1,
        data: problemRates,
        smooth: true,
        itemStyle: {
          color: '#f56c6c'
        }
      }
    ]
  };

  trendChart.setOption(option);
}

function renderDimensionChart() {
  if (!dimensionChartRef.value || !dimensionStats.value) return;

  if (!dimensionChart) {
    dimensionChart = echarts.init(dimensionChartRef.value);
  }

  const data = Object.entries(dimensionStats.value).map(([name, value]: [string, any]) => ({
    name: getDimensionLabel(name),
    value: value.problemCount || 0
  }));

  const option = {
    title: {
      text: '问题分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '问题分布',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  dimensionChart.setOption(option);
}

function renderDimensionBarChart() {
  if (!dimensionBarChartRef.value || !dimensionStats.value) return;

  if (!dimensionBarChart) {
    dimensionBarChart = echarts.init(dimensionBarChartRef.value);
  }

  const dimensions = Object.keys(dimensionStats.value).map(getDimensionLabel);
  const scores = Object.values(dimensionStats.value).map((item: any) => item.score || 0);

  const option = {
    title: {
      text: '维度评分',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: dimensions
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100
    },
    series: [
      {
        name: '评分',
        type: 'bar',
        data: scores,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  };

  dimensionBarChart.setOption(option);
}

function getDimensionLabel(dimension: string): string {
  const map: Record<string, string> = {
    COMPLETENESS: '完整性',
    UNIQUENESS: '唯一性',
    VALIDITY: '有效性',
    CONSISTENCY: '一致性',
    TIMELINESS: '时效性',
    ACCURACY: '准确性'
  };
  return map[dimension] || dimension;
}

watch(visible, val => {
  if (val) {
    loadReport();
  } else {
    if (trendChart) {
      trendChart.dispose();
      trendChart = null;
    }
    if (dimensionChart) {
      dimensionChart.dispose();
      dimensionChart = null;
    }
    if (dimensionBarChart) {
      dimensionBarChart.dispose();
      dimensionBarChart = null;
    }
  }
});
</script>

<style scoped></style>
